package com.energy.analysis.basic.controller;

import com.energy.analysis.basic.entity.*;
import com.energy.analysis.basic.service.CollectService;
import com.energy.analysis.basic.service.PriceService;
import com.energy.analysis.basic.service.StandService;
import com.energy.analysis.basic.service.StationService;
import com.energy.analysis.comm.page.Page;
import com.energy.analysis.comm.returnvalue.DefaultReturnCode;
import com.energy.analysis.comm.returnvalue.ReturnValue;
import com.energy.analysis.comm.utils.DateUtils;
import com.energy.analysis.comm.utils.StringUtils;
import com.energy.analysis.report.entity.CollectDataDay;
import com.energy.analysis.report.service.CollectDataDayService;
import com.energy.analysis.sys.entity.OprInfo;
import com.energy.analysis.sys.service.OprInfoService;
import com.energy.analysis.weather.entity.WeatherData;
import com.energy.analysis.weather.entity.WeatherDataStal;
import com.energy.analysis.weather.service.WeatherService;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private CollectService collectService;

    @Autowired
    private StationService stationService;

    @Autowired
    private StandService standService;

    @Autowired
    private PriceService priceService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private OprInfoService oprInfoService;

    @Autowired
    private CollectDataDayService collectDataDayService;

    @Autowired
    private StationController stationController;

    @RequestMapping("/test")
    @ResponseBody
    public String test(String account) {
        return account + "-aaa";
    }

    @RequestMapping("/test1")
    @ResponseBody
    public ReturnValue<Map<String, Object>> test1(String account) {
        // 取一下机组信息
        List<StandData> standDataList = standService.getStandData();
        int standSize = 0;// 机组数量
        if (standDataList != null && standDataList.size() != 0) {
            standSize = standDataList.size();
        }
        Float ft3q = 0f;// 水
        Float jqi = 0f;// 电
        Float qqi = 0f;// 热
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("eTime", DateUtils.getTodayNow());
        map.put("groupType", 2);// 接机组分组汇
        List<CollectData> collectDataList = collectService.getCollectDate(map);
        for (CollectData collectData : collectDataList) {
            ft3q += collectData.getFt3q();
            jqi += collectData.getJqi();
            qqi += collectData.getQqi();
        }

        PriceData priceData = priceService.getPriceData();

        Float totalquantity = ft3q + jqi + qqi;// 水、电、热总数据
        Float totalAmount = ft3q * priceData.getFt3qPrice() + jqi * priceData.getJqiPrice() + qqi * priceData.getQqiPrice();// 水、电、热总金额

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("ft3q", ft3q);
        retMap.put("jqi", jqi);
        retMap.put("qqi", qqi);
        retMap.put("ft3q_a", ft3q * priceData.getFt3qPrice());
        retMap.put("jqi_a", jqi * priceData.getJqiPrice());
        retMap.put("qqi_a", qqi * priceData.getQqiPrice());

        // return HReturnUtil.creatSuccessful(retMap);
        return new ReturnValue<Map<String, Object>>(retMap);
    }

    @RequestMapping("/login")
    @ResponseBody
    public ReturnValue<OprInfo> login(String account, String pwd) {
        if (account == null || account.length() == 0) {
            return new ReturnValue<>(new DefaultReturnCode(-1, "账号不能为空"));
        }

        // 获取操作员信息
        OprInfo oprInfo = oprInfoService.getByLoginId(account);

        // 1.账号是否存在 00:注销,01:正常 02:锁定
        if (oprInfo == null || StringUtils.isEmpty(oprInfo.getOprSts())) {
            throw new UnknownAccountException();// 1.没找到帐号
        } else if (oprInfo.getOprSts().equals("02")) {// 是否被锁
            throw new LockedAccountException();
        } else if (oprInfo.getOprSts().equals("01")) {
            // 操作员账户正常 do nothing
        } else {
            throw new UnknownAccountException(); // 包含注销操作
        }
        if (oprInfo.checkPwd(pwd)) {
            return new ReturnValue<>(oprInfo);
        }
        return new ReturnValue<>(new DefaultReturnCode(-2, "账号错误"));
    }

    @RequestMapping("/changePwd")
    @ResponseBody
    public ReturnValue<String> changePwd(String account, String oldPwd, String newPwd) {
        // 获取操作员信息
        OprInfo oprInfo = oprInfoService.getByLoginId(account);
        if (oprInfo == null) {
            return new ReturnValue<>(new DefaultReturnCode(-1, "没找到帐号"));
        }
        if (oprInfoService.modifyPassword(oldPwd, newPwd, oprInfo)) {
            return new ReturnValue<>("ok");
        }
        return new ReturnValue<>(new DefaultReturnCode(-2, "原密码错误"));
    }

    /**
     * 换热站信息
     *
     * @return
     */
    @RequestMapping("/stationList")
    @ResponseBody
    public ReturnValue<Map<String, Object>> stationList() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<StationData> stationDataList = stationService.getStationData();
        List<StandData> standDataList = standService.getStandData();
        PriceData priceData = priceService.getPriceData();
        map.put("stationDataList", stationDataList);
        map.put("standDataList", standDataList);
        map.put("priceData", priceData);
        return new ReturnValue<>(map);
    }

    /**
     * 天气概览
     *
     * @return
     */
    @RequestMapping("/weatherIndex")
    @ResponseBody
    public ReturnValue<Map<String, Object>> weatherIndex() {
        Map<String, Object> model = new HashMap<String, Object>();
        WeatherDataStal weatherDataStal = weatherService.findWeatherStalCurr();
        model.put("weatherDataStal", weatherDataStal);
        String tm = weatherDataStal.getCrtTm();
        model.put("shikuang", tm.substring(0, 2) + ":" + tm.substring(2, 4));

        // 风的等级
        String winLevl = "0";
        // 风的名称
        String winName = "";
        if (null != weatherDataStal.getWinSMax()) {
            float bd = weatherDataStal.getWinSMax().floatValue();
            if (bd >= 0 && bd <= 0.2) {
                winLevl = "0";
                winName = "无风";
            } else if (bd >= 0.3 && bd <= 1.5) {
                winLevl = "1";
                winName = "软风";
            } else if (bd >= 1.6 && bd <= 3.3) {
                winLevl = "2";
                winName = "轻风";
            } else if (bd >= 3.4 && bd <= 5.4) {
                winLevl = "3";
                winName = "微风";
            } else if (bd >= 5.5 && bd <= 7.9) {
                winLevl = "4";
                winName = "和风";
            } else if (bd >= 8.0 && bd <= 10.7) {
                winLevl = "5";
                winName = "清风";
            } else if (bd >= 10.8 && bd <= 13.8) {
                winLevl = "6";
                winName = "强风";
            } else if (bd >= 13.9 && bd <= 17.1) {
                winLevl = "7";
                winName = "疾风";
            } else if (bd >= 17.2 && bd <= 20.7) {
                winLevl = "8";
                winName = "大风";
            } else if (bd >= 20.8 && bd <= 24.4) {
                winLevl = "9";
                winName = "烈风";
            } else if (bd >= 24.5) {
                winLevl = "10";
                winName = "狂风";
            }
        }
        BigDecimal temInt = new BigDecimal(weatherDataStal.getTem().intValue());
        model.put("winLevl", winLevl);
        model.put("winName", winName);
        BigDecimal zero = BigDecimal.ZERO;
        BigDecimal pb = new BigDecimal(40);
        BigDecimal dd = new BigDecimal(0.8);
        // 以0度 像素40为标准,每增加一度就会40+0.8 [40 + (温度-zero)*0.8]
        BigDecimal xiangsu = pb.add(temInt.subtract(zero).multiply(dd));
        model.put("xiangsu", xiangsu.toString());
        // 取整的温度
        model.put("wendu", temInt);

        List<WeatherData> weatherDataList = weatherService.getWeather7Day();
        model.put("data7", weatherDataList);
        // 为当天天气
        WeatherData weatherData = weatherDataList.get(3);
        model.put("weatherData", weatherData);
        // 日期
        model.put("dt", weatherData.getCrtDt().substring(6));
        return new ReturnValue<>(model);
    }

    @RequestMapping("/weatherDetail")
    @ResponseBody
    public ReturnValue<List<WeatherData>> weatherDetail() {
        List<WeatherData> weatherDataList = weatherService.getDay4Data();
        return new ReturnValue<>(weatherDataList);
    }

    /**
     * 天气情况查询
     *
     * @param page
     * @return
     */
    @RequestMapping("/weatherList")
    @ResponseBody
    public ReturnValue<List<WeatherData>> weatherList(Page<WeatherData> page, String beginTime, String endTime) {
        page.getParams().put("beginTime", beginTime.replaceAll("-", ""));
        page.getParams().put("endTime", endTime.replaceAll("-", ""));
        weatherService.getAvgTemList(page);
        weatherService.getAvgTemListCount(page);
        return new ReturnValue<>(page.getRows());
    }

    /**
     * 返回日报表
     *
     * @param page
     * @return
     */
    @RequestMapping("/day/list")
    @ResponseBody
    public ReturnValue<List<Map<String, Object>>> dayList(Page<CollectDataDay> page, String searchDateTime) {
        if (StringUtils.isNotEmpty(searchDateTime)) {
            page.getParams().put("dt", new java.sql.Date(DateUtils.toDate(searchDateTime).getTime()).toString());
        }
        page.setRowsMap(collectDataDayService.getDataByDateTime(page));
        page.setTotal(collectDataDayService.getDataByDateTimeCount(page));
        return new ReturnValue<>(page.getRowsMap());
    }

    /**
     * 返回月报表
     *
     * @param page
     * @return
     */
    @RequestMapping("/month/list")
    @ResponseBody
    public ReturnValue<List<Map<String, Object>>> monthList(Page<CollectDataDay> page, String searchDateTime, String stationName) {
        if (StringUtils.isNotEmpty(searchDateTime)) {
            Date date = DateUtils.toDate(searchDateTime);
            // 获取最大日
            java.sql.Date dt = collectDataDayService.getMonthMaxDay(DateUtils.getYear(date), DateUtils.getMonth(date), null, stationName);
            if (dt == null) {
                return new ReturnValue<>(page.getRowsMap());
            }
            page.getParams().put("dt", dt.toString());
            page.getParams().put("stationName", stationName);
        }

        page.setRowsMap(collectDataDayService.getDataByDateTime(page));
        page.setTotal(collectDataDayService.getDataByDateTimeCount(page));
        return new ReturnValue<>(page.getRowsMap());
    }

    /**
     * 返回年报表
     *
     * @param page
     * @return
     */
    @RequestMapping("/year/list")
    @ResponseBody
    public ReturnValue<List<Map<String, Object>>> yearList(Page<CollectDataDay> page, String year, String stationName) {
        if (StringUtils.isNotEmpty(year)) {
            java.sql.Date dt = collectDataDayService.getMonthMaxDay(Integer.parseInt(year), null, null, stationName);
            if (dt == null) {
                return new ReturnValue<>(page.getRowsMap());
            }
            page.getParams().put("dt", dt.toString());
            page.getParams().put("stationName", stationName);
        }
        page.setRowsMap(collectDataDayService.getDataByDateTime(page));
        page.setTotal(collectDataDayService.getDataByDateTimeCount(page));
        return new ReturnValue<>(page.getRowsMap());
    }

    /**
     * 返经济分析报表
     *
     * @param request
     * @param page
     * @return
     */
    @RequestMapping("/econ/list")
    @ResponseBody
    public ReturnValue<List<Map<String, Object>>> econList(HttpServletRequest request, Page<CollectDataDay> page) {
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        String stationName = request.getParameter("stationName");
        java.sql.Date dt = collectDataDayService.getMonthEconMaxDay(beginTime, endTime, stationName);
        if (dt == null) {
            return new ReturnValue<>(page.getRowsMap());
        }
        page.getParams().put("dt", dt.toString());
        page.getParams().put("beginTime", beginTime);
        page.getParams().put("endTime", endTime);
        page.getParams().put("stationName", stationName);
        page.setRowsMap(collectDataDayService.getDataEconByDateTime(page));
        page.setTotal(collectDataDayService.getDataEconByDateTimeCount(page));
        return new ReturnValue<>(page.getRowsMap());
    }

    @RequestMapping("/actualdata")
    @ResponseBody
    public ReturnValue<List<CollectExtendData>> actualdata() {
        List<CollectExtendData> collectExtendDataList = new ArrayList<CollectExtendData>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("eTime", DateUtils.getTodayNow());
        map.put("groupType", 2);// 接机组分组汇总
        stationController.addCollectExtendActualData(collectExtendDataList, map);
        return new ReturnValue<>(collectExtendDataList);
    }

    @RequestMapping("/historydata")
    @ResponseBody
    public ReturnValue<List<CollectExtendData>> historydata(HttpServletRequest request) {
        List<CollectExtendData> collectExtendDataList = new ArrayList<CollectExtendData>();
        Map<String, Object> map = new HashMap<String, Object>();
        String tTime = request.getParameter("eTime") + ":00";
        map.put("eTime", tTime);
        map.put("groupType", 2);// 接机组分组汇总
        stationController.addCollectExtendActualData(collectExtendDataList, map);
        return new ReturnValue<>(collectExtendDataList);
    }

    @RequestMapping("/analysisWater")
    @ResponseBody
    public ReturnValue<List<Map<String, Object>>> analysisWater(HttpServletRequest request, String beginTime, String endTime, String stationName, Page<CollectDataDay> page) {
        page.getParams().put("beginTime", beginTime);
        page.getParams().put("endTime", endTime);
        page.getParams().put("stationName", stationName);
        // page.setLimit(9999999);// 因为需要下载全部页数据
        // page.setOffset(0);
        List<Map<String, Object>> allList = collectDataDayService.getAnalysisWater(page);
        return new ReturnValue<>(allList);
    }

    @RequestMapping("/analysisElectricity")
    @ResponseBody
    public ReturnValue<List<Map<String, Object>>> analysisElectricity(HttpServletRequest request, String beginTime, String endTime, String stationName, Page<CollectDataDay> page) {
        page.getParams().put("beginTime", beginTime);
        page.getParams().put("endTime", endTime);
        page.getParams().put("stationName", stationName);
        // page.setLimit(9999999);// 因为需要下载全部页数据
        // page.setOffset(0);
        List<Map<String, Object>> allList = collectDataDayService.getAnalysisElectricity(page);
        return new ReturnValue<>(allList);
    }

    @RequestMapping("/analysisHeat")
    @ResponseBody
    public ReturnValue<List<Map<String, Object>>> analysisHeat(HttpServletRequest request, String beginTime, String endTime, String stationName, Page<CollectDataDay> page) {
        page.getParams().put("beginTime", beginTime);
        page.getParams().put("endTime", endTime);
        page.getParams().put("stationName", stationName);
        // page.setLimit(9999999);// 因为需要下载全部页数据
        // page.setOffset(0);
        List<Map<String, Object>> allList = collectDataDayService.getAnalysisHeat(page);
        return new ReturnValue<>(allList);
    }
}
